package cn.tianyigps.tianyigpsgatherchecker.service;

import cn.tianyigps.tianyigpsgatherchecker.bean.Condition;
import cn.tianyigps.tianyigpsgatherchecker.bean.EquipmentCheckModel;
import cn.tianyigps.tianyigpsgatherchecker.bean.RuleModel;
import cn.tianyigps.tianyigpsgatherchecker.constant.RuleTypeEnum;
import cn.tianyigps.tianyigpsgatherchecker.dao.RuleDao;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;


@Service
public class CheckerService {

    @Autowired
    RuleDao ruleDao;
    @Autowired
    EquipmentCheckModelService equipmentCheckModelService;
    @Autowired
    GetCarNums getCarNums;
    @Autowired
    AlarmOrNot alarmOrNot;

    public void GatherCheck(String equId) {
        ObjectMapper mapper = new ObjectMapper();
        List<RuleModel<Condition>> listRuleModel = ruleDao.getRules(equId, RuleTypeEnum.GATHER.getType());
        if (StringUtils.isEmpty(listRuleModel))
        {
            return;
        }
        for (RuleModel<Condition> ruleModel : listRuleModel)
        {
            Condition condition = null;
            try {
                condition = mapper.readValue(ruleModel.getCondition().toString(), Condition.class);
                if (StringUtils.isEmpty(condition) || StringUtils.isEmpty(condition.getCar()) || StringUtils.isEmpty(condition.getRadius()) || StringUtils.isEmpty(condition.getGatherTime()))
                    return;

                int gatherTime = Integer.parseInt(condition.getGatherTime()) * 60;
                int radius = Integer.parseInt(condition.getRadius());


                EquipmentCheckModel equipmentCheckModel = equipmentCheckModelService.getEquipmentCheckModelById(equId);
                if (!Optional.ofNullable(equipmentCheckModel).isPresent()) {
                    return;
                }
                HashSet set = getCarNums.getCarNumbers(equipmentCheckModel,gatherTime,radius);
                if(set==null||set.isEmpty())
                    return;

                if(!alarmOrNot.check(equId,ruleModel,equipmentCheckModel,set)){
                    return;
                }
                //运行到最后时已报警

            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }
    }

}
